<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace app\common\model;

use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use think\Cache;

class Slide extends Base
{
    protected $table = 'wechatadmin.system_slide';
    protected $getSlideVersionCache = 'new_slide1:';
    protected $getGoddessStateAdvCache = 'goddess_state_adv:';
    protected $questionAnswerAdvCache = 'question_answer_adv:';
    protected $getStartPageCache = 'start_page';
    protected $getStartPageVersionCache = 'start_page1:';
    protected $getSlideImgTextCache = 'slide_img_content1:';

    /**
     * 轮播图根据版本显示
     * @param array $map
     * @return array
     * @throws ApiException
     */
    public function getSlideVersion(array $map = [])
    {
        $header = request()->header();
        $data = false;
        if ($this->cache_on >= 1) $data = Cache::get($this->getSlideVersionCache . $header['app-type'] . '_' . $header['version']);
        if ($data === false)
        {
            $where = ['sv.type' => 1, 'v.type' => $header['app-type'], 'v.version_name' => 'V' . $header['version'], 's.status' => 1, 's.cid' => 1];
            try
            {
                $field = 's.id,s.hg,s.name,s.photo,s.description,s.link,s.target,s.image,s.image2,s.content';

                $data = $this->field($field)->alias('s')
                    ->join('wechatadmin.system_slide_version sv', 's.id=sv.sid')
                    ->join('wechatadmin.system_app_version v', 'sv.vid=v.id')
                    ->where($where)
                    ->order('sort DESC')->selectOrFail();
                $data = json_decode(json_encode($data, true), true);
            }
            catch (\Exception $e)
            {
//                \think\Log::write('banner获取失败：' . $e->getMessage(), 'slide_error', true);
                $data = [];

//                throw new ApiException('banner获取失败');
            }

            if ($this->cache_on >= 1)
                Cache::set($this->getSlideVersionCache . $header['app-type'] . '_' . $header['version'], $data, 86400 * 3);

        }
        if (!empty($data))
        {
            $ves = Util::CheckAppVersion('2.6.0');
            $isHg = Util::AppIsPassShowV1();
            $resList = [];
            foreach ($data as $k => $d)
            {
                $d['hg'] = $d['hg'] ?? 0;
                if ($isHg && $d['hg'] != 1)
                {   // 合规情况 过滤合规隐藏的数据
                    continue;
                }
                //2.6.0版本banner更换新尺寸
                if ($ves !== '小')
                {
                    $photos = is_string($d['photo']) ? unserialize($d['photo']) : $d['photo'];
                    if (!empty($photos[2]))
                    {
                        $temp = explode('|', $photos[2]);
                        $data[$k]['image'] = $temp[0];
                    }
                }

                if (isset($map['id']) && $map['id'] > 0 && $d['id'] == $map['id'])
                {
                    return $d;
                    throw new ApiException('数据获取失败');
                }
                $data[$k]['link'] = htmlspecialchars_decode($d['link']);
                $data[$k]['content'] = htmlspecialchars_decode($d['content']);
                unset($data[$k]['photo'], $data[$k]['hg']);
                $resList[] = $data[$k];
            }
            $data = $resList;
        }


        return $data;
    }

    /**
     * 首页视频根据版本显示
     * @return array
     * @throws ApiException
     */
    public function getGoddessStateAdv()
    {
        $header = request()->header();
        $data = false;
        if ($this->cache_on >= 1) $data = Cache::get($this->getGoddessStateAdvCache . $header['app-type'] . '_' . $header['version']);

        if ($data === false)
        {
            $where = ['sv.type' => 1, 'v.type' => $header['app-type'], 'v.version_name' => 'V' . $header['version'], 's.status' => 1, 's.cid' => 4];
            try
            {
                $field = 's.id,s.name,s.photo,s.description,s.link,s.target,s.image,s.image2,s.content,s.sort';

                $data = $this->field($field)->alias('s')
                    ->join('wechatadmin.system_slide_version sv', 's.id=sv.sid')
                    ->join('wechatadmin.system_app_version v', 'sv.vid=v.id')
                    ->where($where)
                    ->order('sort DESC')->selectOrFail();
                $data = json_decode(json_encode($data, true), true);
            }
            catch (\Exception $e)
            {
//                \think\Log::write('banner获取失败：' . $e->getMessage(), 'slide_error', true);
                $data = [];
            }

            if ($this->cache_on >= 1)
                Cache::set($this->getGoddessStateAdvCache . $header['app-type'] . '_' . $header['version'], $data, 86400 * 3);

        }

        return $data ?: [];
    }

    /**
     * 问答首页banner根据版本显示
     * @return array
     */
    public function getQuestionAnswerAdv()
    {
        $header = request()->header();
        $data = false;
        if ($this->cache_on >= 1) $data = Cache::get($this->questionAnswerAdvCache . $header['app-type'] . '_' . $header['version']);

        if ($data === false)
        {
            $where = ['sv.type' => 1, 'v.type' => $header['app-type'], 'v.version_name' => 'V' . $header['version'], 's.status' => 1, 's.cid' => 5];
            try
            {
                $field = 's.id,s.name,s.photo,s.description,s.link,s.target,s.image,s.image2,s.content,s.sort';

                $data = $this->field($field)->alias('s')
                    ->join('wechatadmin.system_slide_version sv', 's.id=sv.sid')
                    ->join('wechatadmin.system_app_version v', 'sv.vid=v.id')
                    ->where($where)
                    ->order('sort DESC')->selectOrFail();
                $data = json_decode(json_encode($data, true), true);
            }
            catch (\Exception $e)
            {
//                \think\Log::write('banner获取失败：' . $e->getMessage(), 'slide_error', true);
                $data = [];
            }

            if ($this->cache_on >= 1)
                Cache::set($this->questionAnswerAdvCache . $header['app-type'] . '_' . $header['version'], $data, 86400 * 3);

        }

        if (!empty($data))
        {
            foreach ($data as $k => $d)
            {
                $data[$k]['link'] = htmlspecialchars_decode($d['link']);
                $data[$k]['content'] = htmlspecialchars_decode($d['content']);
            }
        }

        return $data ?: [];
    }

    /**
     * 轮播图不根据版本显示
     * @return array
     */
    public function getStartPage()
    {
        $data = false;
        if ($this->cache_on >= 1)
        {
            $data = Cache::get($this->getStartPageCache);
        }
        if ($data === false)
        {
            try
            {
                $field = 'id,name,description,link,target,image,image2,photo';

                $data = $this->field($field)
                    ->where(['status' => 1, 'cid' => 2])
                    ->order('id desc')
                    ->findOrFail()->toArray();
                $data['link'] = htmlspecialchars_decode($data['link']);
            }
            catch (\Exception $e)
            {
                //当缓存不存在的时候（后台隐藏幸运之城），ios 有bug，为了粉丝测试，不再次提交到testflight上，后台返回数据
                $data = [
                    'name' => '',
                    'description' => '',
                    'link' => '',
                    'target' => '',
                    'image' => '',
                    'image2' => '',
                    'photo' => '',
                ];
            }
            if ($this->cache_on >= 1)
            {
                Cache::set($this->getStartPageCache, $data, 86400 * 3);
            }
        }
        return $data;
    }

    /**
     * 根据版本获取启动页
     * @return array
     */
    public function getStartPageVersion()
    {
        $header = request()->header();
        /**
         * 修复IOS 未知情况下，未传递header无法获取启动页的问题
         */
        if (strpos($header['user-agent'], 'XZNSProphet') !== false)
        {
            //XZNSProphet/1.9.0 (iPhone; iOS 12.3.1; Scale/2.00)
            $appType = 'ios';
            $iosLength = strlen('XZNSProphet');
            $end = strpos($header['user-agent'], ' ') - $iosLength;
            $version = substr($header['user-agent'], $iosLength + 1, $end - 1);
        } else
        {
            $appType = $header['app-type'];
            $version = $header['version'];
        }

        $data = false;
        if ($this->cache_on >= 1)
        {
            $data = Cache::get($this->getStartPageVersionCache . $appType . '_' . $version);
        }
        if ($data === false)
        {
            $where = ['sv.type' => 1, 'v.type' => $appType, 'v.version_name' => 'V' . $version, 's.status' => 1, 's.cid' => 2];
            try
            {
                $field = 's.id,s.name,s.description,s.hg,s.link,s.target,s.image,s.image2,s.photo';

                $data = $this
                    ->alias('s')
                    ->field($field)
                    ->join('wechatadmin.system_slide_version sv', 's.id=sv.sid')
                    ->join('wechatadmin.system_app_version v', 'sv.vid=v.id')
                    ->where($where)
                    ->order('s.id desc')
                    ->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                //当缓存不存在的时候（后台隐藏幸运之城），ios 有bug，为了粉丝测试，不再次提交到testflight上，后台返回数据
                $data = [
                    'id' => '',
                    'name' => '',
                    'hg' => 1,
                    'description' => '',
                    'link' => '',
                    'target' => '',
                    'image' => '',
                    'image2' => '',
                    'photo' => '',
                ];
            }
            if ($this->cache_on >= 1)
            {
                Cache::set($this->getStartPageVersionCache . $appType . '_' . $version, $data, 86400 * 3);
            }
        }
        return $data;
    }

    /**
     * 获取指定轮播图图文内容
     * @param $cid
     * @param $id
     * @return array|bool|mixed
     */
    public function getWebSlideInfo($cid, $id)
    {
        $data = false;
        if ($this->cache_on >= 1) $data = Cache::get($this->getSlideImgTextCache . $cid . '-' . $id);

        if ($data === false)
        {
            try
            {
                $field = 'id,name,status,description,link,target,image,content';

                $data = $this->field($field)->where(['cid' => $cid, 'id' => $id])->order('sort DESC')->findOrFail()->toArray();
                $data['link'] = htmlspecialchars_decode($data['link']);
                $data['content'] = htmlspecialchars_decode($data['content']);
                if ($this->cache_on >= 1)
                    Cache::set($this->getSlideImgTextCache . $cid . '-' . $id, $data, 86400 * 3);

            }
            catch (\Exception $e)
            {
//                \think\Log::write('banner获取失败：' . $e->getMessage(), 'slide_error', true);

                return false;
            }
        }
        return $data;
    }
}
